package org.company.management.ui;

import org.company.management.controller.EmployeeGroupJpaController;
import org.company.management.controller.EmployeeJpaController;
import org.company.management.controller.FileController;
import org.company.management.controller.StatusLineController;
import org.company.management.controller.UiController;
import org.company.management.entity.Employee;
import org.company.management.entity.EmployeeGroup;
import org.company.management.utilities.CustomValidatedText;
import org.company.management.utilities.LastNameValidator;
import org.company.management.utilities.NameValidator;
import org.company.management.utilities.PhoneValidator;
import org.company.management.utilities.Strings;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.EditorPart;
import org.eclipse.wb.swt.ResourceManager;
import org.eclipse.wb.swt.layout.grouplayout.GroupLayout;
import org.eclipse.wb.swt.layout.grouplayout.LayoutStyle;

/**
 * @author Paner
 *
 */
public class UpdateEmployeeEditor extends EditorPart implements SelectionListener {

	public static final String ID = Strings.updateEmployeeEditorId;
	
	private Button _backButton;
	private Button _addButton;
	private Label _imageLabel;
	private CustomValidatedText _nameText;
	private CustomValidatedText _lastNameText;
	private CustomValidatedText _phoneText;
	private Combo _groupCombo;
	private Employee _employee;
	private Button _loadPhoto;
	private Group _employeesGroup;

	/* 
	 * Constructor, sets editor`s image
	 */
	public UpdateEmployeeEditor() {
		setTitleImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.editUserPicture16x16));
		
	}

	@Override
	public void doSave(IProgressMonitor monitor) {
		// TODO Auto-generated method stub

	}

	@Override
	public void doSaveAs() {
		// TODO Auto-generated method stub

	}

	@Override
	public void init(IEditorSite site, IEditorInput input)
			throws PartInitException {
		try
		{
			EditorInput inp = (EditorInput)input;
			_employee = (Employee)inp.getParticipant();
		}
		catch(Exception ex)
		{
			throw new RuntimeException("Wrong input");
		}

		setSite(site);
		setInput(input);

	}

	@Override
	public boolean isDirty() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isSaveAsAllowed() {
		// TODO Auto-generated method stub
		return false;
	}

	
	@Override
	public void createPartControl(Composite parent) 
	{
		createControls(parent);
		createLayout(parent);
		fillEditor();
		
	}
			
	/*
	 * Creates widgets
	 */
	private void createControls(Composite parent) 
	{
		_employeesGroup = new Group(parent, SWT.NONE);
		_employeesGroup.setText(Strings.employee);
		
		_backButton = new Button(parent, SWT.NONE);
		_backButton.setToolTipText(Strings.backTooltip);
		_backButton.setImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.backButtonPicture32x32));
		_backButton.addSelectionListener(this);
		
		_addButton = new Button(parent, SWT.NONE);
		_addButton.setToolTipText(Strings.confirmTooltip);
		_addButton.setImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.confirmButtonPicture32x32));
		_addButton.addSelectionListener(this);

		_loadPhoto = new Button(_employeesGroup, SWT.NONE);
		_loadPhoto.setToolTipText(Strings.addPhotoTooltip);
		_loadPhoto.setImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.openPhotoPicture32x32));
		_loadPhoto.setBounds(292, 230, 52, 25);
		_loadPhoto.addSelectionListener(this);
		
		_nameText = new CustomValidatedText(_employeesGroup, new NameValidator());
		_nameText.setBounds(114, 63, 239, 21);
		
		_lastNameText = new CustomValidatedText(_employeesGroup, new LastNameValidator());
		_lastNameText.setBounds(114, 116, 239, 21);
		
		_phoneText = new CustomValidatedText(_employeesGroup, new PhoneValidator());
		_phoneText.setBounds(114, 171, 239, 21);
		
		_imageLabel = new Label(_employeesGroup, SWT.NONE);
		_imageLabel.setBounds(114, 198, 172, 89);
		
		
		Label label = new Label(_employeesGroup, SWT.NONE);
		label.setText(Strings.name);
		label.setBounds(29, 66, 55, 15);
		
		Label lastnameLabel = new Label(_employeesGroup, SWT.NONE);
		lastnameLabel.setText(Strings.lastName);
		lastnameLabel.setBounds(29, 119, 55, 15);
		
		Label phoneLabel = new Label(_employeesGroup, SWT.NONE);
		phoneLabel.setText(Strings.phone);
		phoneLabel.setBounds(29, 174, 79, 15);
		
		Label groupLabel = new Label(_employeesGroup, SWT.NONE);
		groupLabel.setText(Strings.group);
		groupLabel.setBounds(29, 296, 55, 15);
		
		_groupCombo = new Combo(_employeesGroup, SWT.READ_ONLY);
		_groupCombo.setBounds(114, 293, 239, 23);
		
	}
	
	/*
	 * Creates layout
	 */
	private void createLayout(Composite parent) 
	{
		GroupLayout gl_parent = new GroupLayout(parent);
		gl_parent.setHorizontalGroup(
			gl_parent.createParallelGroup(GroupLayout.TRAILING)
				.add(gl_parent.createSequentialGroup()
					.addContainerGap()
					.add(_backButton)
					.addContainerGap(546, Short.MAX_VALUE))
				.add(gl_parent.createSequentialGroup()
					.addContainerGap(523, Short.MAX_VALUE)
					.add(_addButton)
					.addContainerGap())
				.add(GroupLayout.LEADING, gl_parent.createSequentialGroup()
					.add(92)
					.add(_employeesGroup, GroupLayout.PREFERRED_SIZE, 388, GroupLayout.PREFERRED_SIZE)
					.addContainerGap(114, Short.MAX_VALUE))
		);
		gl_parent.setVerticalGroup(
			gl_parent.createParallelGroup(GroupLayout.TRAILING)
				.add(gl_parent.createSequentialGroup()
					.addContainerGap()
					.add(_backButton)
					.add(59)
					.add(_employeesGroup, GroupLayout.PREFERRED_SIZE, 326, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(LayoutStyle.RELATED, 13, Short.MAX_VALUE)
					.add(_addButton)
					.addContainerGap())
		);
		parent.setLayout(gl_parent);
		
	}
	
	/*
	 * Fills the components of the editor
	 */
	private void fillEditor() 
	{
		try
		{
			_nameText.setText(_employee.getName());
			_lastNameText.setText(_employee.getLastname());
			_phoneText.setText(_employee.getPhone());
			
			//Set image
			if( _employee.getPicture() != null)
			{
				Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
				Image employeeImage = new Image(shell.getDisplay(), _employee.getPicture());  
				
				_imageLabel.setImage(employeeImage);
				_imageLabel.setData(_employee.getPicture());
			}
			
			//Fill combo with values
			EmployeeGroupJpaController employeeGroupDao = new EmployeeGroupJpaController();
			_groupCombo.add("");
			
			for(EmployeeGroup employeeGroup : employeeGroupDao.findEmployeeGroupEntities())
			{
				_groupCombo.add(employeeGroup.getName());
				_groupCombo.setData(employeeGroup);
			}
			
			if(_employee.getGroupid() != null)
			{
				_groupCombo.setText(_employee.getGroupid().getName());
			}
			
		}
		catch(Exception ex)
		{
			//throw;
			System.out.println(ex.getMessage().toString());
		}
		
	}
	
	/*
	 * Checks that required fields are filled
	 */
	private boolean validateUserInput()
	{
		boolean proceed = false;
		if(_nameText.isValid()  &&  _lastNameText.isValid() && _phoneText.isValid())
		{
			proceed = true;
		}
		
		return proceed;
		
	}

	
	@Override
	public void widgetSelected(SelectionEvent e) 
	{
		Object selectedWidget = e.getSource();
		if(selectedWidget == _backButton)
		{
			UiController.showEditor(Strings.gallery, EmployeeGalleryEditor.ID);
		}
		else if(selectedWidget == _addButton)
		{
			if(validateUserInput())
			{
				try
				{
					//Update employee for user given values
					_employee.setName(_nameText.getText());
					_employee.setLastname(_lastNameText.getText());
					_employee.setPhone(_phoneText.getText());

					String imagePath = null;
					imagePath = (String) _imageLabel.getData();
					
					_employee.setPicture(imagePath);
					
					if(_groupCombo.getText() != null && _groupCombo.getText().length() != 0)
					{
						_employee.setGroupid((EmployeeGroup)_groupCombo.getData());
					}
					else
					{
						_employee.setGroupid(null);
					}
					
					EmployeeJpaController employeeDao = new EmployeeJpaController();
					employeeDao.edit(_employee);
					
					StatusLineController.setStatusLine(getEditorSite(), Strings.validUpdatedInputMessage);

				}
				catch (Exception ex)
				{
					ex.printStackTrace();
				}
				
			}
			else
			{
				StatusLineController.setStatusLine(getEditorSite(), Strings.invalidInputMessage);
			}
		}
		else if(selectedWidget == _loadPhoto)
		{
			try
			{
				//Set image
				FileController.openFile();
				String selectedFile = FileController.copyFile();
				Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
				Image selectedImage = new Image(shell.getDisplay(), selectedFile);
				_imageLabel.setData(selectedFile);
				_imageLabel.setImage(selectedImage);
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
			}
		}
	}

	@Override
	public void widgetDefaultSelected(SelectionEvent e) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void setFocus() {
		// TODO Auto-generated method stub

	}

}
